<?php

namespace app\api\controller;

use app\admin\model\Club;
use app\admin\model\Order;
use app\admin\model\TeacherArea;
use app\admin\model\TeacherCollection;
use app\admin\model\TeacherDetail;
use app\admin\model\TeacherSubscribe;
use app\common\controller\Api;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\Html;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Config;

/**
 * 身份信息接口
 */
class IdentityInfo extends Api
{
    /**
     * 临时文件列表，用于延迟删除
     */
    private $tempFiles = [];
    protected $noNeedLogin = ['test', 'test_image_download', 'generate_word_document', 'downloadWord'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function identity_info(){
        $all = $this->request->param();
        if(!isset($all['identity_type'])||!$all['identity_type']){
            $this->error('身份不能为空');
        }
        if($all['identity_type'] == '普通用户'){
            $this->error('普通用户无身份数据信息');
        }
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $find = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->find();
        if(!$find){
            $this->error('用户身份不存在');
        }
        $find['avatar'] = $user['avatar'];
        $find['img_arr'] = $find['imgs'] ? explode(',',$find['imgs']) : [];
        $find['teacher_certification_arr'] = $find['teacher_certification'] ? explode(',',$find['teacher_certification']) : [];
        $find['diploma_arr'] = $find['diploma'] ? explode(',',$find['diploma']) : [];
        $find['occupational_qualifications_arr'] = $find['occupational_qualifications'] ? explode(',',$find['occupational_qualifications']) : [];
        $find['professional_skill'] = $find['professional_skill'] ? explode(',',$find['professional_skill']) : [];
        $find['health_certificate'] = $find['health_certificate'] ? explode(',',$find['health_certificate']) : [];
        $find['identity_card_img'] = $find['identity_card_img'] ? explode(',',$find['identity_card_img']) : [];
        $find['no_crime'] = $find['no_crime'] ? explode(',',$find['no_crime']) : [];
        $find['personal_resume'] = $find['personal_resume'] ? $find['personal_resume'] : '';
        $find['educational_back'] = $find['educational_back'] ? $find['educational_back'] : '';
        $find['work_experience'] = $find['work_experience'] ? $find['work_experience'] : '';
        $find['certificate_reward'] = $find['certificate_reward'] ? $find['certificate_reward'] : '';
        $find['self_assessment'] = $find['self_assessment'] ? $find['self_assessment'] : '';
        $find['tag_me'] = $find['tag_me'] ? $find['tag_me'] : '';
        $find['jxjh'] = $find['jxjh'] ? $find['jxjh'] : '';
        $find['age'] = $find['age'] ? $find['age'] : '';
        $find['invitation_code'] = isset($user['invitation_code']) ? $user['invitation_code'] : '';

        $user_find = \app\admin\model\User::where(['id'=>$user['id']])->find();
        if($user_find['gender'] == 1){
            $sex = '男';
        }else{
            $sex = '女';
        }
        $find['sex'] = $sex;
//        $find['work_time'] = $find['work_time'] ? $find['work_time'].'年' : '';
        $find['education_background'] = $find['education_background'] ? $find['education_background'] : '';

        $area = $find['area'] ? explode(',',$find['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k=>$v){
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v].',' : '';
        }
        $find['area_name'] = trim($area_name,',');

        $find['puser'] = [];
        if($user_find['p_user_id']){
            $p_user = \app\admin\model\User::where(['id'=>$user_find['p_user_id']])->find();
            $find['puser'] = $p_user;
        }
        // 返回显示状态
        $find['main_status'] = isset($find['main_status']) ? $find['main_status'] : 1;
        $this->success('身份数据',$find);
    }

    public function identity_up(){
        $all = $this->request->param();
        if(!isset($all['name'])||!$all['name']){
            $this->error('姓名不能为空');
        }
//        if(!isset($all['identity_type'])||!$all['identity_type']){
//            $this->error('身份不能为空');
//        }
        $all['identity_type'] = '教师';
        if(!isset($all['phone'])||!$all['phone']){
            $this->error('电话不能为空');
        }
        if(!isset($all['appointment_time_week'])||!$all['appointment_time_week']){
            $this->error('可约时间不能为空');
        }
        if(!isset($all['appointment_time'])||!$all['appointment_time']){
            $this->error('可约时间不能为空');
        }

        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $find = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->find();
        if(!$find){
            $this->error('用户身份不存在');
        }
        $data = [];
        if(isset($all['school'])&&$all['school']){
            $data['school'] = $all['school'];//学校
        }
        if(isset($all['name'])&&$all['name']){
            $data['name'] = $all['name'];//姓名
        }
        if(isset($all['phone'])&&$all['phone']){
            $data['phone'] = $all['phone'];//电话
        }
        if($find['phone']!=$data['phone']){
            $phone_find = \app\admin\model\IdentityInfo::where(['phone'=>$data['phone']])->where("user_id != {$user['id']}")->find();
            if($phone_find){
                $this->error('手机号已被其他账号使用');
            }
            $user_find = \app\admin\model\User::where(['mobile'=>$data['phone']])->where("id != {$user['id']}")->find();
            if($user_find){
                $this->error('手机号已被其他账号使用');
            }
        }
        if(isset($all['club_one_id'])&&$all['club_one_id']){
            $data['club_one_id'] = $all['club_one_id'];//社团id
        }
        if(isset($all['club_two_id'])&&$all['club_two_id']){
            $data['club_two_id'] = $all['club_two_id'];//子社团id
        }
        if(isset($all['hourly_rate'])&&$all['hourly_rate']){
            $data['hourly_rate'] = $all['hourly_rate'];//课时费用
        }
        if(isset($all['appointment_time_week'])&&$all['appointment_time_week']){
            $data['appointment_time_week'] = $all['appointment_time_week'];//可约时间（周）
        }
        if(isset($all['appointment_time'])&&$all['appointment_time']){
            $data['appointment_time'] = $all['appointment_time'];//可约时间（时）
        }
        if(isset($all['teacher_certification'])&&$all['teacher_certification']){
            $data['teacher_certification'] = $all['teacher_certification'];//教师资格证
        }
        if(isset($all['diploma'])&&$all['diploma']){
            $data['diploma'] = $all['diploma'];//毕业证书
        }
        if(isset($all['occupational_qualifications'])&&$all['occupational_qualifications']){
            $data['occupational_qualifications'] = $all['occupational_qualifications'];//预备知识要求
        }
        if(isset($all['course_outline'])&&$all['course_outline']){
            $data['course_outline'] = $all['course_outline'];//课程简介
        }
        if(isset($all['teaching_objectives'])&&$all['teaching_objectives']){
            $data['teaching_objectives'] = $all['teaching_objectives'];//教学目标
        }
        if(isset($all['knowledge_requirements'])&&$all['knowledge_requirements']){
            $data['knowledge_requirements'] = $all['knowledge_requirements'];//预备知识要求
        }
        if(isset($all['imgs'])&&$all['imgs']){
            $data['imgs'] = $all['imgs'];//封面图
        }

        if(isset($all['personal_resume'])&&$all['personal_resume']){
            $data['personal_resume'] = $all['personal_resume'];//个人简历
        }
        if(isset($all['educational_back'])&&$all['educational_back']){
            $data['educational_back'] = $all['educational_back'];//教育背景
        }
        if(isset($all['work_experience'])&&$all['work_experience']){
            $data['work_experience'] = $all['work_experience'];//工作经历
        }
        if(isset($all['certificate_reward'])&&$all['certificate_reward']){
            $data['certificate_reward'] = $all['certificate_reward'];//证书奖励
        }
        if(isset($all['self_assessment'])&&$all['self_assessment']){
            $data['self_assessment'] = $all['self_assessment'];//自我评价
        }
        if(isset($all['professional_skill'])&&$all['professional_skill']){
            $data['professional_skill'] = $all['professional_skill'];//专业技能证书
        }
        if(isset($all['health_certificate'])&&$all['health_certificate']){
            $data['health_certificate'] = $all['health_certificate'];//健康证
        }
        if(isset($all['identity_card_img'])&&$all['identity_card_img']){
            $data['identity_card_img'] = $all['identity_card_img'];//身份证复印件
        }
        if(isset($all['no_crime'])&&$all['no_crime']){
            $data['no_crime'] = $all['no_crime'];//无犯罪证明
        }
        if(isset($all['area'])&&$all['area']){
            $data['area'] = $all['area'];//区域
        }
        if(isset($all['tag_me'])&&$all['tag_me']){
            $data['tag_me'] = $all['tag_me'];//区域
        }
        if(isset($all['jxjh'])&&$all['jxjh']){
            $data['jxjh'] = $all['jxjh'];//教学计划
        }
        if(isset($all['age'])&&$all['age']){
            $data['age'] = $all['age'];//年龄
        }

        $update = [];
        if(isset($all['sex'])&&$all['sex']){
            if($all['sex'] == '男'){
                $update['gender'] = 1;
            }else {
                $update['gender'] = 0;
            }
            unset($all['sex']);
        }
//        if(isset($all['work_time'])&&$all['work_time']){
//            $data['work_time'] = (int)$all['work_time'];//工作经验时长
//        }
        if(isset($all['education_background'])&&$all['education_background']){
            $data['education_background'] = $all['education_background'];//最高学历
        }
        // 处理显示状态
        if(isset($all['main_status'])){
            $data['main_status'] = (int)$all['main_status'];//显示状态 1显示 2不显示
        }

        if($user['identity_type'] == '教师'){
            if($find['appointment_time_week'] != $all['appointment_time_week']){
                $week = explode(',',$all['appointment_time_week']);
                $identity_info_model = new \app\admin\model\IdentityInfo();
                $week_id_arr = $identity_info_model->getWeekList();
                $is_int_name = 0;
                foreach ($week as $k=>$v){
                    $is_int = (int)$v;
                    if($is_int>0){
                        $week[$k] = $week_id_arr[$v];
                        $is_int_name = 1;
                    }
                }
                if($is_int_name == 1){
                    $data['appointment_time_week'] = implode(',',$week);//可约时间（周）
                }
                $sub = TeacherSubscribe::up_subscribe($week,$user['id']);
                if($sub['code'] == 0){
                    $this->error($sub['msg']);
                }
            }
        }
        $res = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->update($data);

        $update['nickname'] = $all['name'];
        if(isset($all['avatar'])&&$all['avatar']){
            $update['avatar'] = $all['avatar'];
        }
        if($find['phone']!=$data['phone']){
            $update['mobile'] = $data['phone'];
            $phone_user_find = \app\admin\model\User::where(['id'=>$user['id']])->find();
            if($phone_user_find['username'] == $phone_user_find['mobile']){
                $update['username'] = $data['phone'];
            }
        }
        $user_res = \app\admin\model\User::where(['id'=>$user['id']])->update($update);
        if($res||$user_res){
            $info_find = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->find();
            if($info_find['name']&&$info_find['phone']&&$info_find['club_one_id']&&$info_find['club_two_id']&&$info_find['teacher_certification'] &&$info_find['diploma']&&$info_find['occupational_qualifications']&&$info_find['professional_skill']&& $info_find['health_certificate']&&$info_find['identity_card_img']&&$info_find['no_crime']){
                $info_find['is_all'] = '是';
            }else{
                $info_find['is_all'] = '否';
            }
            
            // 修改成功后，添加队列任务生成Word文档
            if ($all['identity_type'] == '教师') {
                $detail = \app\admin\model\TeacherDetail::where(['info_id'=>$info_find['id']])->select();
                foreach ($detail as $k=>$v){
                    \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $info_find['user_id'],'detail_id'=>$v['id']], 'default');
                }
                // 使用队列异步生成Word文档
//                \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $user['id']], 'default');
            }
            
            $this->success('修改成功',$res);
        }else{
            $this->error('修改失败');
        }
    }

    //身份数据更新下拉数据
    public function identity_up_pull(){
        $club = Club::with('dtl')->order('sort','asc')->select();

        $data = [];
        $data['club'] = $club;
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        if($user['identity_type'] == '教师'){
            $week = [1,2,3,4,5,6,7];
            $subscribe = TeacherSubscribe::where(['teacher_id'=>$user['id']])->where('class_id >0')->column('week');
            $week_arr = array_diff($week,$subscribe);
            $week_arr = array_values($week_arr);
            sort($week_arr);
            $data['week'] = $week_arr;
            $identity_info_model = new \app\admin\model\IdentityInfo();
            $getWeekList = $identity_info_model->getWeekList();
            $week_name = [];
            foreach ($week_arr as $k=>$v){
                $week_name[$v] = isset($getWeekList[$v]) ? $getWeekList[$v] : '';
            }
            $data['week_name'] = $week_name;
        }
        $area_arr = TeacherArea::get_arr();
        $data['area'] = $area_arr;
        $data['education_background'] = ['小学','初中','高中','中专','大专','本科','硕士','博士'];
        $data['education_background_arr'] = [
            [
                'id'=>'小学',
                'name'=>'小学',
            ],
            [
                'id'=>'初中',
                'name'=>'初中',
            ],
            [
                'id'=>'高中',
                'name'=>'高中',
            ],
            [
                'id'=>'中专',
                'name'=>'中专',
            ],
            [
                'id'=>'大专',
                'name'=>'大专',
            ],
            [
                'id'=>'本科',
                'name'=>'本科',
            ],
            [
                'id'=>'硕士',
                'name'=>'硕士',
            ],
            [
                'id'=>'博士',
                'name'=>'博士',
            ],
        ];
        $this->success('修改成功',$data);
    }

    //获取教师身份数据
    public function get_identity_info(){
        $all = $this->request->param();
        if(!isset($all['id'])||!$all['id']){
            $this->error('用户id必传');
        }
        $find = TeacherDetail::where(['id'=>$all['id']])->with(['identity','clubDtlS'])->find();
//        $find = \app\admin\model\IdentityInfo::where(['user_id'=>$all['user_id'],'identity_type'=>'教师'])->with(['user','clubDtlS'])->find();
        if(!$find){
            $this->error('用户身份不存在');
        }
        
        // 基本信息
        $find['user_id'] = $find['identity']['user_id'] ? $find['identity']['user_id'] : '';
        $find['name'] = $find['identity']['name'] ? $find['identity']['name'] : ''; // 教师姓名
        $find['avatar'] = isset($find['identity']['user']) ? $find['identity']['user']['avatar'] : '';
        $find['club_dtl_name'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['name'] : '';
        $find['stage'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['stage'] : '';
        $find['grade'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['grade'] : '';
        $find['phone'] = $find['identity']['phone'] ? $find['identity']['phone'] : ''; // 电话
        $find['school'] = $find['identity']['school'] ? $find['identity']['school'] : ''; // 学校名称
        
        // 课程表字段（原始字符串和数组）
        if(!$find['imgs']){
            $find['imgs'] = isset($find['club_dtl_s']['img_url']) ? $find['club_dtl_s']['img_url'] : '';
        }
//        $find['imgs'] = $find['imgs'] ? $find['imgs'] : ''; // 形象照原始字符串
        $find['img_arr'] = $find['imgs'] ? explode(',',$find['imgs']) : [];
        $find['teacher_certification'] = $find['teacher_certification'] ? $find['teacher_certification'] : ''; // 教师资格证原始字符串
        $find['teacher_certification_arr'] = $find['teacher_certification'] ? explode(',',$find['teacher_certification']) : [];
        $find['diploma'] = $find['diploma'] ? $find['diploma'] : ''; // 毕业证书原始字符串
        $find['diploma_arr'] = $find['diploma'] ? explode(',',$find['diploma']) : [];
        $find['occupational_qualifications'] = $find['occupational_qualifications'] ? $find['occupational_qualifications'] : ''; // 获奖证书原始字符串
        $find['occupational_qualifications_arr'] = $find['occupational_qualifications'] ? explode(',',$find['occupational_qualifications']) : [];
        $find['professional_skill'] = $find['professional_skill'] ? $find['professional_skill'] : ''; // 专业技能证书原始字符串
        $find['professional_skill_arr'] = $find['professional_skill'] ? explode(',',$find['professional_skill']) : [];
        
        // 主表字段（IdentityInfo）
        $find['health_certificate'] = $find['identity']['health_certificate'] ? $find['identity']['health_certificate'] : ''; // 健康证原始字符串
        $find['health_certificate_arr'] = $find['identity']['health_certificate'] ? explode(',',$find['identity']['health_certificate']) : [];
        $find['identity_card_img'] = $find['identity']['identity_card_img'] ? $find['identity']['identity_card_img'] : ''; // 身份证原始字符串
        $find['identity_card_img_arr'] = $find['identity']['identity_card_img'] ? explode(',',$find['identity']['identity_card_img']) : [];
        $find['no_crime'] = $find['identity']['no_crime'] ? $find['identity']['no_crime'] : ''; // 无犯罪证明原始字符串
        $find['no_crime_arr'] = $find['identity']['no_crime'] ? explode(',',$find['identity']['no_crime']) : [];
        
        // 课程表其他字段
        $find['personal_resume'] = $find['personal_resume'] ? $find['personal_resume'] : '';
        $find['educational_back'] = $find['educational_back'] ? $find['educational_back'] : '';
        $find['work_experience'] = $find['work_experience'] ? $find['work_experience'] : '';
        $find['certificate_reward'] = $find['certificate_reward'] ? $find['certificate_reward'] : '';
        $find['self_assessment'] = $find['self_assessment'] ? $find['self_assessment'] : '';
        $find['tag_me'] = $find['tag_me'] ? $find['tag_me'] : ''; // 自评标签原始字符串
        $find['tag_me_arr'] = $find['tag_me'] ? explode(',',$find['tag_me']) : []; // 自评标签数组
        $find['jxjh'] = $find['jxjh'] ? $find['jxjh'] : '';
        $find['work_time'] = $find['work_time'] ? $find['work_time'] : ''; // 工作年限原始值
        $find['work_time_display'] = $find['work_time'] ? $find['work_time'].'年' : ''; // 工作年限显示值
        $find['hourly_rate'] = $find['hourly_rate'] ? $find['hourly_rate'] : ''; // 课时费用
        $find['is_premium'] = isset($find['is_premium']) ? $find['is_premium'] : 0; // 是否精品
        $find['people'] = isset($find['people']) ? $find['people'] : 0; // 人数
        $find['score'] = $this->formatScore($find['score']); // 评分（5分制）
        $find['detail_status'] = isset($find['detail_status']) ? $find['detail_status'] : 1; // 显示状态
        $find['order_num'] = isset($find['order_num']) ? $find['order_num'] : 0; // 订单数
        $find['addtime'] = $find['addtime'] ? $find['addtime'] : ''; // 添加时间
        
        // 主表其他字段（IdentityInfo）
        $find['age'] = $find['identity']['age'] ? $find['identity']['age'] : '';
        $find['education_background'] = $find['identity']['education_background'] ? $find['identity']['education_background'] : '';
        $find['appointment_time_week'] = $find['identity']['appointment_time_week'] ? $find['identity']['appointment_time_week'] : ''; // 可约时间（周）
        $find['appointment_time'] = $find['identity']['appointment_time'] ? $find['identity']['appointment_time'] : ''; // 可约时间（时）
        $find['tag'] = $find['identity']['tag'] ? $find['identity']['tag'] : ''; // 标签原始字符串
        $find['tag_arr'] = $find['identity']['tag'] ? explode(',',$find['identity']['tag']) : []; // 标签数组
        $find['main_status'] = isset($find['identity']['main_status']) ? $find['identity']['main_status'] : 1; // 显示状态
        $find['birthday'] = $find['identity']['birthday'] ? $find['identity']['birthday'] : ''; // 生日
        $find['word_file'] = $find['identity']['word_file'] ? $find['identity']['word_file'] : ''; // 文档地址
        $find['is_all'] = $find['identity']['is_all'] ? $find['identity']['is_all'] : '否'; // 是否上传完整

        // 性别
        $user_find = \app\admin\model\User::where(['id'=>$find['identity']['user_id']])->find();
        if($user_find && isset($user_find['gender'])){
            $find['sex'] = ($user_find['gender'] == 1) ? '男' : '女';
        } else {
            $find['sex'] = '';
        }

        // 区域处理
        $area = $find['identity']['area'] ? explode(',',$find['identity']['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k=>$v){
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v].',' : '';
        }
        $find['area'] = $find['identity']['area'] ? $find['identity']['area'] : ''; // 区域原始字符串
        $find['area_arr'] = $area; // 区域数组
        $find['area_name'] = trim($area_name,','); // 区域名称


        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        $order_find = Order::where(['teacher_detail_id'=>$all['id'],'user_id'=>$user['id'],'pay_status'=>2])->find();
        //是否购买，可以查看详细信息
        if($order_find){
            $find['readable'] = 1;
        }else{
            $find['readable'] = 0;
        }
        $tco = \app\admin\model\TeacherCollection::where(['teacher_detail_id'=>$all['id'],'user_id'=>$user['id']])->find();
        //是否收藏
        if($tco){
            $find['is_collection'] = 1;
        }else{
            $find['is_collection'] = 0;
        }
        if(!$find['course_duration']){
            $defaultDuration = Config::get('course.default_course_duration', '');
            $find['course_duration'] = $defaultDuration ? $defaultDuration : 40;
        }else{
            $find['course_duration'] = (int)$find['course_duration'];
        }
        //增加浏览记录
        \app\admin\model\BrowsingHistory::addHistory($all['id'],$user['id']);
        unset($find['identity'],$find['club_dtl_s']);
        $this->success('教师数据',$find);
    }

    //获取教师身份数据（主表和课程表分开）
    public function get_teacher_info_with_details(){
        $all = $this->request->param();
        
        // 支持通过 id 或 user_id 查询
        $info_id = null;
        if(isset($all['id']) && $all['id']){
            $info_id = $all['id'];
        } elseif(isset($all['user_id']) && $all['user_id']){
            $identityInfo = \app\admin\model\IdentityInfo::where(['user_id' => $all['user_id'], 'identity_type' => '教师'])->find();
            if(!$identityInfo){
                $this->error('用户身份不存在');
            }
            $info_id = $identityInfo['id'];
        } else {
            $this->error('id 或 user_id 必传');
        }

        // 查询主表（IdentityInfo）
        $main = \app\admin\model\IdentityInfo::where(['id' => $info_id, 'identity_type' => '教师'])
            ->with(['user'])
            ->find();
        
        if(!$main){
            $this->error('教师身份不存在');
        }

        // 查询所有课程（TeacherDetail）
        $dtlList = TeacherDetail::where(['info_id' => $info_id])
            ->with(['clubDtlS', 'club'])
            ->order('id', 'asc')
            ->select();

        // 处理主表数据
        $mainData = [];
        $mainData['id'] = $main['id'];
        $mainData['user_id'] = $main['user_id'] ? $main['user_id'] : '';
        $mainData['name'] = $main['name'] ? $main['name'] : '';
        $mainData['avatar'] = isset($main['user']) ? $main['user']['avatar'] : '';
        $mainData['phone'] = $main['phone'] ? $main['phone'] : '';
        $mainData['school'] = $main['school'] ? $main['school'] : '';
        $mainData['identity_type'] = $main['identity_type'] ? $main['identity_type'] : '';
        $dtlLists = TeacherDetail::where(['info_id' => $info_id])
            ->with(['clubDtlS'])
            ->order('id', 'asc')
            ->find();
        // 处理主表的数组字段
        if(!$main['imgs']){
            $main['imgs'] = isset($dtlLists['club_dtl_s']['img_url']) ? $dtlLists['club_dtl_s']['img_url'] : '';
        }
        $mainData['imgs'] = $main['imgs'] ? $main['imgs'] : ''; // 原始字符串
        $mainData['img_arr'] = $main['imgs'] ? explode(',', $main['imgs']) : [];
        $mainData['health_certificate'] = $main['health_certificate'] ? explode(',', $main['health_certificate']) : [];
        $mainData['identity_card_img'] = $main['identity_card_img'] ? explode(',', $main['identity_card_img']) : [];
        $mainData['no_crime'] = $main['no_crime'] ? explode(',', $main['no_crime']) : [];
        
        // 主表其他字段
        $mainData['appointment_time_week'] = $main['appointment_time_week'] ? $main['appointment_time_week'] : '';
        $mainData['appointment_time'] = $main['appointment_time'] ? $main['appointment_time'] : '';
        $mainData['age'] = $main['age'] ? $main['age'] : '';
        $mainData['education_background'] = $main['education_background'] ? $main['education_background'] : '';
        $mainData['main_status'] = isset($main['main_status']) ? $main['main_status'] : 1; // 显示状态 1显示 2隐藏
        $mainData['tag'] = $main['tag'] ? $main['tag'] : ''; // 标签
        $mainData['tag_arr'] = $main['tag'] ? explode(',', $main['tag']) : []; // 标签数组
        $mainData['main_score'] = $main['main_score'];
        $mainData['score'] = isset($main['main_score']) ? $this->formatScore($main['main_score']) : ''; // 评分（5分制）
        $mainData['user_score'] = $main['user_score'] ? $main['user_score'] : ''; // 用户评分
        $mainData['people'] = isset($main['people']) ? $main['people'] : 0; // 人数
        $mainData['is_premium'] = isset($main['is_premium']) ? $main['is_premium'] : 0; // 是否精品
        $mainData['birthday'] = $main['birthday'] ? $main['birthday'] : ''; // 生日
        $mainData['word_file'] = $main['word_file'] ? $main['word_file'] : ''; // 文档地址
        $mainData['addtime'] = $main['addtime'] ? $main['addtime'] : ''; // 添加时间
        $mainData['sort'] = isset($main['sort']) ? $main['sort'] : 0; // 排序
        $mainData['is_all'] = $main['is_all'] ? $main['is_all'] : '否'; // 是否上传完整
        
        // 性别
        $user_find = \app\admin\model\User::where(['id' => $main['user_id']])->find();
        if($user_find && isset($user_find['gender'])){
            $mainData['sex'] = ($user_find['gender'] == 1) ? '男' : '女';
        } else {
            $mainData['sex'] = '';
        }
        
        // 区域处理
        $area = $main['area'] ? explode(',', $main['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k => $v){
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v].',' : '';
        }
        $mainData['area'] = $main['area'] ? $main['area'] : '';
        $mainData['area_arr'] = $area;
        $mainData['area_name'] = trim($area_name, ',');

        $club_name = [];
        // 处理课程数据（dtl数组）
        $dtlData = [];
        foreach ($dtlList as $k => $v){
            $dtlData[$k]['id'] = $v['id']; // 课程id
            $dtlData[$k]['info_id'] = $v['info_id']; // 身份id
            $dtlData[$k]['club_one_id'] = $v['club_one_id']; // 社团id
            $dtlData[$k]['club_one_name'] =  isset($v['club']) ? $v['club']['name'] : ''; // 社团名称
            $dtlData[$k]['club_two_id'] = $v['club_two_id']; // 子社团id
            $dtlData[$k]['club_two_name'] = $club_name_arr =isset($v['club_dtl_s']['name']) ? $v['club_dtl_s']['name'] : ''; // 子社团名称
            $club_name[] = $club_name_arr;
            $dtlData[$k]['club_two_log'] = isset($v['club_dtl_s']['img_url']) ? $v['club_dtl_s']['img_url'] : ''; // 子社团logo
            $dtlData[$k]['stage'] = isset($v['club_dtl_s']['stage']) ? $v['club_dtl_s']['stage'] : ''; // 阶段
            $dtlData[$k]['grade'] = isset($v['club_dtl_s']['grade']) ? $v['club_dtl_s']['grade'] : ''; // 年级
            $dtlData[$k]['hourly_rate'] = $v['hourly_rate'] ? $v['hourly_rate'] : ''; // 课时费用
            $dtlData[$k]['is_premium'] = isset($v['is_premium']) ? $v['is_premium'] : 0; // 是否精品
            $dtlData[$k]['people'] = isset($v['people']) ? $v['people'] : 0; // 人数
            $dtlData[$k]['score'] = $this->formatScore($v['score']); // 评分（5分制）
            $dtlData[$k]['work_time'] = $v['work_time'] ? $v['work_time'] : ''; // 工作年限（原始值）
            $dtlData[$k]['work_time_display'] = $v['work_time'] ? $v['work_time'].'年' : ''; // 工作年限（显示值）
            $dtlData[$k]['club_dtl_name'] = isset($v['club_dtl_s']['name']) ? $v['club_dtl_s']['name'] : ''; // 子社团名称（兼容字段）
            
            // 处理课程表的数组字段
            $dtlData[$k]['imgs'] = $v['imgs'] ? $v['imgs'] : ''; // 形象照（原始字符串）
            $dtlData[$k]['img_arr'] = $v['imgs'] ? explode(',', $v['imgs']) : []; // 形象照图组
            $dtlData[$k]['teacher_certification'] = $v['teacher_certification'] ? $v['teacher_certification'] : ''; // 教师资格证（原始字符串）
            $dtlData[$k]['teacher_certification_arr'] = $v['teacher_certification'] ? explode(',', $v['teacher_certification']) : []; // 教师资格证图组
            $dtlData[$k]['diploma'] = $v['diploma'] ? $v['diploma'] : ''; // 毕业证书（原始字符串）
            $dtlData[$k]['diploma_arr'] = $v['diploma'] ? explode(',', $v['diploma']) : []; // 毕业证书图组
            $dtlData[$k]['occupational_qualifications'] = $v['occupational_qualifications'] ? $v['occupational_qualifications'] : ''; // 获奖证书（原始字符串）
            $dtlData[$k]['occupational_qualifications_arr'] = $v['occupational_qualifications'] ? explode(',', $v['occupational_qualifications']) : []; // 获奖证书图组
            $dtlData[$k]['professional_skill'] = $v['professional_skill'] ? $v['professional_skill'] : ''; // 专业技能证书（原始字符串）
            $dtlData[$k]['professional_skill_arr'] = $v['professional_skill'] ? explode(',', $v['professional_skill']) : []; // 专业技能证书图组
            
            // 课程表其他字段
            $dtlData[$k]['course_outline'] = $v['course_outline'] ? $v['course_outline'] : ''; // 课程大纲
            $dtlData[$k]['teaching_objectives'] = $v['teaching_objectives'] ? $v['teaching_objectives'] : ''; // 教学目标
            $dtlData[$k]['knowledge_requirements'] = $v['knowledge_requirements'] ? $v['knowledge_requirements'] : ''; // 预备知识要求
            $dtlData[$k]['personal_resume'] = $v['personal_resume'] ? $v['personal_resume'] : ''; // 个人简历
            $dtlData[$k]['educational_back'] = $v['educational_back'] ? $v['educational_back'] : ''; // 教育背景
            $dtlData[$k]['work_experience'] = $v['work_experience'] ? $v['work_experience'] : ''; // 工作经历
            $dtlData[$k]['certificate_reward'] = $v['certificate_reward'] ? $v['certificate_reward'] : ''; // 证书奖励
            $dtlData[$k]['self_assessment'] = $v['self_assessment'] ? $v['self_assessment'] : ''; // 自我评价
            $dtlData[$k]['tag_me'] = $v['tag_me'] ? $v['tag_me'] : ''; // 自评标签
            $dtlData[$k]['tag_me_arr'] = $v['tag_me'] ? explode(',', $v['tag_me']) : []; // 自评标签数组
            $dtlData[$k]['jxjh'] = $v['jxjh'] ? $v['jxjh'] : ''; // 教学计划
            $dtlData[$k]['addtime'] = $v['addtime'] ? $v['addtime'] : ''; // 添加时间
            $dtlData[$k]['detail_status'] = isset($v['detail_status']) ? $v['detail_status'] : 1; // 显示状态 1显示 2隐藏
            $dtlData[$k]['order_num'] = isset($v['order_num']) ? $v['order_num'] : 0; // 订单数
        }

        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }

        $collected_teacher_detail_ids = [];
        if ($current_user_id) {
            // 收集所有teacher_detail_id
            $all_teacher_detail_ids = [];
            foreach ($dtlList as $v) {
                $all_teacher_detail_ids[] = $v['id'];
            }
            // 批量查询收藏状态
            if (!empty($all_teacher_detail_ids)) {
                $collected_teacher_detail_ids = TeacherCollection::where(['user_id' => $current_user_id])
                    ->whereIn('teacher_detail_id', array_unique($all_teacher_detail_ids))
                    ->column('teacher_detail_id');
            }
        }
        $teacher_detail = [];
        foreach ($dtlList as $kk=>$vv){
            if(isset($vv['club_dtl_s']['name'])&&$vv['club_dtl_s']['name']){
                $club_dtl_name[] = $vv['club_dtl_s']['name'];
            }
            $teacher_detail[$kk]['id'] = $vv['id'];
            $teacher_detail[$kk]['info_id'] = $vv['info_id'];
            $teacher_detail[$kk]['hourly_rate'] = $vv['hourly_rate'];
            $teacher_detail[$kk]['club_name'] = isset($vv['club_dtl_s']['name']) ? $vv['club_dtl_s']['name'] : '';
            $teacher_detail[$kk]['club_img_url'] = isset($vv['club_dtl_s']['img_url']) ? $vv['club_dtl_s']['img_url'] : '';
            $teacher_detail[$kk]['is_premium'] = $vv['is_premium'];
            $teacher_detail[$kk]['people'] = $vv['people'];
            if($vv['work_time']>0){
                $teacher_detail[$kk]['work_time'] = $vv['work_time'].'年';
            }else{
                $teacher_detail[$kk]['work_time'] = '';
            }
            // 检查该课程是否被收藏
            $is_collected = 2; // 默认2=未收藏
            if ($current_user_id && isset($vv['id']) && in_array($vv['id'], $collected_teacher_detail_ids)) {
                $is_collected = 1; // 1=已收藏
            }
            $teacher_detail[$kk]['is_collected'] = $is_collected; // 1已收藏，2未收藏
        }
        $mainData['club_name_arr'] = array_values(array_unique($club_name));
        // 构建返回数据
        $result = [
            'main' => $mainData,
            'data' => $teacher_detail,
            'dtl' => array_values($dtlData)
        ];

        // 如果用户已登录，添加收藏和购买状态
        $user = $this->auth->getUser();
        if(isset($user['id']) && $user['id']){
            // 查询用户收藏的所有课程ID
            $collected_ids = \app\admin\model\TeacherCollection::where(['user_id' => $user['id']])
                ->whereIn('teacher_detail_id', array_column($dtlData, 'id'))
                ->column('teacher_detail_id');
            
            // 查询用户已购买的课程ID
            $purchased_ids = Order::where(['user_id' => $user['id'], 'pay_status' => 2])
                ->whereIn('teacher_detail_id', array_column($dtlData, 'id'))
                ->column('teacher_detail_id');
            
            // 为每个课程添加收藏和购买状态
            foreach ($result['dtl'] as $k => $dtl){
                $result['dtl'][$k]['is_collected'] = in_array($dtl['id'], $collected_ids) ? 1 : 2; // 1已收藏 2未收藏
                $result['dtl'][$k]['is_purchased'] = in_array($dtl['id'], $purchased_ids) ? 1 : 0; // 1已购买 0未购买
                $result['dtl'][$k]['readable'] = in_array($dtl['id'], $purchased_ids) ? 1 : 0; // 是否可查看详细信息
            }
        } else {
            // 未登录用户，默认未收藏、未购买
            foreach ($result['dtl'] as $k => $dtl){
                $result['dtl'][$k]['is_collected'] = 2; // 2未收藏
                $result['dtl'][$k]['is_purchased'] = 0; // 0未购买
                $result['dtl'][$k]['readable'] = 0; // 不可查看详细信息
            }
        }

        $arr = [];
        foreach ($result['dtl'] as $k=>$v){
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['name'] = $v['club_two_name'];
            $arr[$k]['data'] = $v;
        }
        $result['dtl'] = $arr;
        $this->success('教师数据', $result);
    }

    protected function formatScore($score)
    {
        if ($score === null || $score === '') {
            return $score;
        }
        if (is_numeric($score)) {
            $score = (float)$score;

            // 最简单最傻瓜式的判断
            // 小于等于0 -> 0
            if ($score <= 0) {
                return '0.0';
            }

            // 大于等于10 -> 5
            if ($score >= 10) {
                return '5.0';
            }

            // 其他情况：向下取整得到整数部分
            $intPart = (int)floor($score);

            // 判断是否为整数（分数的小数部分是否接近0）
            $isInteger = abs($score - $intPart) < 0.001;

//            if ($isInteger) {
//                // 整数：n * 0.5
//                // 1 -> 0.5, 2 -> 1.0, 3 -> 1.5, 4 -> 2.0, ...
                $formattedScore = $intPart * 0.5;
//            } else {
//                // 小数：(n+1) * 0.5
//                // 0.1-0.9 -> 0.5, 1.1-1.9 -> 1.0, 2.1-2.9 -> 1.5, ...
//                $formattedScore = ($intPart + 1) * 0.5;
//            }

            return number_format($formattedScore, 1, '.', '');
        }
        return $score;
    }

    public function get_identity_info_old(){
        $all = $this->request->param();
        if(!isset($all['user_id'])||!$all['user_id']){
            $this->error('用户id必传');
        }
        $find = \app\admin\model\IdentityInfo::where(['user_id'=>$all['user_id'],'identity_type'=>'教师'])->with(['user','clubDtlS'])->find();
        if(!$find){
            $this->error('用户身份不存在');
        }
        $find['avatar'] = isset($find['user']) ? $find['user']['avatar'] : '';
        $find['club_dtl_name'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['name'] : '';
        $find['stage'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['stage'] : '';
        $find['grade'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['grade'] : '';
        $find['img_arr'] = $find['imgs'] ? explode(',',$find['imgs']) : [];
        $find['teacher_certification_arr'] = $find['teacher_certification'] ? explode(',',$find['teacher_certification']) : [];
        $find['diploma_arr'] = $find['diploma'] ? explode(',',$find['diploma']) : [];
        $find['occupational_qualifications_arr'] = $find['occupational_qualifications'] ? explode(',',$find['occupational_qualifications']) : [];


        $find['professional_skill'] = $find['professional_skill'] ? explode(',',$find['professional_skill']) : [];
        $find['health_certificate'] = $find['health_certificate'] ? explode(',',$find['health_certificate']) : [];
        $find['identity_card_img'] = $find['identity_card_img'] ? explode(',',$find['identity_card_img']) : [];
        $find['no_crime'] = $find['no_crime'] ? explode(',',$find['no_crime']) : [];
        $find['personal_resume'] = $find['personal_resume'] ? $find['personal_resume'] : '';
        $find['educational_back'] = $find['educational_back'] ? $find['educational_back'] : '';
        $find['work_experience'] = $find['work_experience'] ? $find['work_experience'] : '';
        $find['certificate_reward'] = $find['certificate_reward'] ? $find['certificate_reward'] : '';
        $find['self_assessment'] = $find['self_assessment'] ? $find['self_assessment'] : '';
        $find['tag_me'] = $find['tag_me'] ? $find['tag_me'] : '';
        $find['jxjh'] = $find['jxjh'] ? $find['jxjh'] : '';
        $find['age'] = $find['age'] ? $find['age'] : '';

        $user_find = \app\admin\model\User::where(['id'=>$all['user_id']])->find();
        if($user_find['gender'] == 1){
            $sex = '男';
        }else{
            $sex = '女';
        }
        $find['sex'] = $sex;

        $find['work_time'] = $find['work_time'] ? $find['work_time'].'年' : '';
        $find['education_background'] = $find['education_background'] ? $find['education_background'] : '';


        $area = $find['area'] ? explode(',',$find['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k=>$v){
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v].',' : '';
        }
        $find['area_name'] = trim($area_name,',');


        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        $order_find = Order::where(['teacher_id'=>$all['user_id'],'user_id'=>$user['id'],'pay_status'=>2])->find();
        if($order_find){
            $find['readable'] = 1;
        }else{
            $find['readable'] = 0;
        }

        unset($find['user'],$find['club_dtl_s']);
        $this->success('教师数据',$find);
    }

    //获取自己课程列表
    public function teacher_detail_list(){
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        //查看身份主表
        $info = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>'教师'])->find();
        //根据身份查询课程表
        $query_res = TeacherDetail::where(['info_id'=>$info['id']])
            ->with(['identity','club','clubDtl'])
            ->order('id','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();

        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id'] = $v['id'];//课程id
            $arr[$k]['info_id'] = $v['info_id'];//身份id
            $arr[$k]['club_one_id'] = $v['club_one_id'];//社团id
            $arr[$k]['club_one_name'] = $v['club']['name'];//社团
            $arr[$k]['club_two_id'] = $v['club_two_id'];//子社团id
            $arr[$k]['club_two_name'] = $v['club_dtl']['name'];//子社团
            $arr[$k]['club_two_log'] = $v['club_dtl']['img_url'];//子社团log图
            $arr[$k]['hourly_rate'] = $v['hourly_rate'];//课时费用
            $arr[$k]['teacher_certification'] = $v['teacher_certification'];//教师资格证
            $arr[$k]['teacher_certification_arr'] = $v['teacher_certification'] ? explode(',',$v['teacher_certification']) : [];//教师资格证图组
            $arr[$k]['diploma'] = $v['diploma'];//毕业证书
            $arr[$k]['diploma_arr'] = $v['diploma'] ? explode(',',$v['diploma']) : [];//毕业证书图组
            $arr[$k]['occupational_qualifications'] = $v['occupational_qualifications'];//获奖证书
            $arr[$k]['occupational_qualifications_arr'] = $v['occupational_qualifications'] ? explode(',',$v['occupational_qualifications']) : [];//获奖证书图组
            $arr[$k]['course_outline'] = $v['course_outline'];//课程大纲
            $arr[$k]['teaching_objectives'] = $v['teaching_objectives'];//教学目标
            $arr[$k]['knowledge_requirements'] = $v['knowledge_requirements'];//预备知识要求
            $arr[$k]['imgs'] = $v['imgs'];//形象照
            $arr[$k]['imgs_arr'] = $v['imgs'] ? explode(',',$v['imgs']) : [];//形象照图组
            $arr[$k]['tag'] = '';//标签
            $arr[$k]['tag_arr'] = [];//标签数组
            $arr[$k]['personal_resume'] = $v['personal_resume'];//个人简历
            $arr[$k]['professional_skill'] = $v['professional_skill'];//专业技能证书
            $arr[$k]['professional_skill_arr'] = $v['professional_skill'] ? explode(',',$v['professional_skill']) : [];//专业技能证书图组
            $arr[$k]['educational_back'] = $v['educational_back'];//教育背景
            $arr[$k]['work_experience'] = $v['work_experience'];//工作经历
            $arr[$k]['certificate_reward'] = $v['certificate_reward'];//证书奖励
            $arr[$k]['self_assessment'] = $v['self_assessment'];//自我评价
            $arr[$k]['tag_me'] = $v['tag_me'];//自评标签
            $arr[$k]['is_premium'] = $v['is_premium'];//是否精品
            $arr[$k]['tag_me_arr'] = $v['tag_me'] ? explode(',',$v['tag_me']) : [];//自评标签数组
            $arr[$k]['addtime'] = $v['addtime'];//添加时间
            $arr[$k]['detail_status'] = isset($v['detail_status']) ? $v['detail_status'] : 1;//显示状态 1显示 2不显示
        }

        $count = $query_res->total();
        $data = [];
        $data['list'] = $arr;
        $data['count'] = $count;
        $this->success('课程列表',$data);
    }

    //添加课程
    public function add_teacher_detail(){
        $all = $this->request->param();
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        //查看身份主表
        $identityInfo = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>'教师'])->find();
        if(!$identityInfo){
            $this->error('用户身份不存在');
        }
        $all['info_id'] = $identityInfo['id'];
        if(!isset($all['club_one_id'])||!$all['club_one_id']){
            $this->error('社团id不能为空');
        }
        if(!isset($all['club_two_id'])||!$all['club_two_id']){
            $this->error('子社团id不能为空');
        }

        
        // 准备数据
        $data = [];
        $data['info_id'] = $all['info_id'];
        $data['club_one_id'] = $all['club_one_id'];
        $data['club_two_id'] = $all['club_two_id'];
        
        if(isset($all['hourly_rate'])&&$all['hourly_rate']){
            $data['hourly_rate'] = $all['hourly_rate'];
        }
        if(isset($all['teacher_certification'])&&$all['teacher_certification']){
            $data['teacher_certification'] = $all['teacher_certification'];
        }
        if(isset($all['diploma'])&&$all['diploma']){
            $data['diploma'] = $all['diploma'];
        }
        if(isset($all['occupational_qualifications'])&&$all['occupational_qualifications']){
            $data['occupational_qualifications'] = $all['occupational_qualifications'];
        }
        if(isset($all['course_outline'])&&$all['course_outline']){
            $data['course_outline'] = $all['course_outline'];
        }
        if(isset($all['teaching_objectives'])&&$all['teaching_objectives']){
            $data['teaching_objectives'] = $all['teaching_objectives'];
        }
        if(isset($all['knowledge_requirements'])&&$all['knowledge_requirements']){
            $data['knowledge_requirements'] = $all['knowledge_requirements'];
        }
        if(isset($all['imgs'])&&$all['imgs']){
            $data['imgs'] = $all['imgs'];
        }
        if(isset($all['tag'])&&$all['tag']){
            $data['tag'] = $all['tag'];
        }
        if(isset($all['personal_resume'])&&$all['personal_resume']){
            $data['personal_resume'] = $all['personal_resume'];
        }
        if(isset($all['professional_skill'])&&$all['professional_skill']){
            $data['professional_skill'] = $all['professional_skill'];
        }
        if(isset($all['educational_back'])&&$all['educational_back']){
            $data['educational_back'] = $all['educational_back'];
        }
        if(isset($all['work_experience'])&&$all['work_experience']){
            $data['work_experience'] = $all['work_experience'];
        }
        if(isset($all['certificate_reward'])&&$all['certificate_reward']){
            $data['certificate_reward'] = $all['certificate_reward'];
        }
        if(isset($all['self_assessment'])&&$all['self_assessment']){
            $data['self_assessment'] = $all['self_assessment'];
        }
        if(isset($all['tag_me'])&&$all['tag_me']){
            $data['tag_me'] = $all['tag_me'];
        }
        if(isset($all['jxjh'])&&$all['jxjh']){
            $data['jxjh'] = $all['jxjh'];
        }
        if(isset($all['work_time'])&&$all['work_time']){
            $data['work_time'] = $all['work_time'];
        }
        if(isset($all['education_background'])&&$all['education_background']){
            $data['education_background'] = $all['education_background'];
        }
        if(isset($all['is_premium'])&&$all['is_premium']){
            $data['is_premium'] = $all['is_premium'];
        }
        if(isset($all['sort'])&&$all['sort']){
            $data['sort'] = $all['sort'];
        }
        if(isset($all['score'])&&$all['score']){
            $data['score'] = $all['score'];
        }
        
        // 唯一性校验：同一教师不可同时存在 社团id 和 精品配置 相同的数据
        // 组合条件：info_id + club_two_id + is_premium
        $checkInfoId    = $data['info_id'];
        $checkClubTwoId = $data['club_two_id'];
        $checkIsPremium = isset($data['is_premium']) ? $data['is_premium'] : 0;
        if ($checkInfoId && $checkClubTwoId) {
            $exists = TeacherDetail::where([
                    'info_id'     => $checkInfoId,
                    'club_two_id' => $checkClubTwoId,
                    'is_premium'  => $checkIsPremium,
                ])->find();
            if ($exists) {
                $this->error('当前教师已存在相同的社团和精品设置');
            }
        }
        
        $data['addtime'] = date('Y-m-d H:i:s');
        
        // 检查是否上传完整
        $detailComplete = $data['club_one_id'] && $data['club_two_id'] && 
                         isset($data['teacher_certification']) && $data['teacher_certification'] &&
                         isset($data['diploma']) && $data['diploma'] &&
                         isset($data['occupational_qualifications']) && $data['occupational_qualifications'] &&
                         isset($data['professional_skill']) && $data['professional_skill'];
        
        $identityComplete = !empty($identityInfo['health_certificate']) && 
                           !empty($identityInfo['identity_card_img']) && 
                           !empty($identityInfo['no_crime']);
        
        $data['is_all'] = ($detailComplete && $identityComplete) ? '是' : '否';
        
        // 保存数据
        $result = TeacherDetail::create($data);
        if(isset($all['hourly_rate'])&&$all['hourly_rate']){
            $td_h = \app\admin\model\TeacherDetail::where(['info_id'=>$data['info_id']])->where("hourly_rate>0")->order('hourly_rate','asc')->find();
            if($td_h){
                if($td_h['hourly_rate']>$all['hourly_rate']){
                    \app\admin\model\IdentityInfo::where(['id'=>$data['info_id']])->update(['lowest_hourly_rate'=>$all['hourly_rate']]);
                }
            }
        }
        if($result){
            // 生成Word文档
            \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $identityInfo['user_id'],'detail_id'=>$result->id], 'default');
            $this->success('添加成功',['id'=>$result->id]);
        }else{
            $this->error('添加失败');
        }
    }

    //查看课程
    public function get_teacher_detail(){
        $all = $this->request->param();
        if(!isset($all['id'])||!$all['id']){
            $this->error('课程id必传');
        }
        
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        
        $find = TeacherDetail::where(['id'=>$all['id']])->with(['identity','clubDtlS','clubs'])->find();
        if(!$find){
            $this->error('课程不存在');
        }
        
        // 验证权限：只有创建者可以查看
        if($find['identity']['user_id'] != $user['id']){
            $this->error('无权查看该课程');
        }
        
        // 处理数据格式
        $find['user_id'] = $find['identity']['user_id'] ? $find['identity']['user_id'] : '';
        $find['avatar'] = isset($find['identity']['user']) ? $find['identity']['user']['avatar'] : '';
        $find['club_dtl_name'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['name'] : '';
        $find['club_one_name'] = isset($find['club']) ? $find['club']['name'] : '';
        $find['stage'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['stage'] : '';
        $find['grade'] = isset($find['club_dtl_s']) ? $find['club_dtl_s']['grade'] : '';
        $find['img_arr'] = $find['imgs'] ? explode(',',$find['imgs']) : [];
        $find['teacher_certification_arr'] = $find['teacher_certification'] ? explode(',',$find['teacher_certification']) : [];
        $find['diploma_arr'] = $find['diploma'] ? explode(',',$find['diploma']) : [];
        $find['occupational_qualifications_arr'] = $find['occupational_qualifications'] ? explode(',',$find['occupational_qualifications']) : [];
        $find['professional_skill_arr'] = $find['professional_skill'] ? explode(',',$find['professional_skill']) : [];
        $find['tag_arr'] = [];
        $find['tag_me_arr'] = $find['tag_me'] ? explode(',',$find['tag_me']) : [];
        $find['personal_resume'] = $find['personal_resume'] ? $find['personal_resume'] : '';
        $find['educational_back'] = $find['educational_back'] ? $find['educational_back'] : '';
        $find['work_experience'] = $find['work_experience'] ? $find['work_experience'] : '';
        $find['certificate_reward'] = $find['certificate_reward'] ? $find['certificate_reward'] : '';
        $find['self_assessment'] = $find['self_assessment'] ? $find['self_assessment'] : '';
        $find['tag_me'] = $find['tag_me'] ? $find['tag_me'] : '';
        $find['jxjh'] = $find['jxjh'] ? $find['jxjh'] : '';

        $find['work_time'] = $find['work_time'] ? $find['work_time'].'年' : '';

        
        unset($find['identity'],$find['club_dtl_s'],$find['club'],$find['appointment_time_week'],$find['appointment_time']);
        unset($find['sort'],$find['score'],$find['user_score'],$find['people'],$find['area'],$find['is_all'],$find['no_crime']);
        unset($find['education_background'],$find['score'],$find['user_score']);
        unset($find['word_file'],$find['order_num'],$find['identity_card_img'],$find['health_certificate']);
        unset($find['knowledge_requirements'],$find['personal_resume']);
        $this->success('课程数据',$find);
    }

    //修改课程
    public function update_teacher_detail(){
        $all = $this->request->param();
        
        if(!isset($all['id'])||!$all['id']){
            $this->error('课程id不能为空');
        }
        
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        
        // 查询课程是否存在
        $find = TeacherDetail::where(['id'=>$all['id']])->with(['identity'])->find();
        if(!$find){
            $this->error('课程不存在');
        }
        
        // 验证权限：只有创建者可以修改
        if($find['identity']['user_id'] != $user['id']){
            $this->error('无权修改该课程');
        }
        
        // 准备更新数据
        $data = [];
        
        if(isset($all['club_one_id'])&&$all['club_one_id']){
            $data['club_one_id'] = $all['club_one_id'];
        }
        if(isset($all['club_two_id'])&&$all['club_two_id']){
            $data['club_two_id'] = $all['club_two_id'];
        }
        if(isset($all['hourly_rate'])&&$all['hourly_rate']){
            $data['hourly_rate'] = $all['hourly_rate'];
        }
        if(isset($all['appointment_time_week'])&&$all['appointment_time_week']){
            $data['appointment_time_week'] = $all['appointment_time_week'];
        }
        if(isset($all['appointment_time'])&&$all['appointment_time']){
            $data['appointment_time'] = $all['appointment_time'];
        }
        if(isset($all['teacher_certification'])){
            $data['teacher_certification'] = $all['teacher_certification'];
        }
        if(isset($all['diploma'])){
            $data['diploma'] = $all['diploma'];
        }
        if(isset($all['occupational_qualifications'])){
            $data['occupational_qualifications'] = $all['occupational_qualifications'];
        }
        if(isset($all['course_outline'])){
            $data['course_outline'] = $all['course_outline'];
        }
        if(isset($all['teaching_objectives'])){
            $data['teaching_objectives'] = $all['teaching_objectives'];
        }
        if(isset($all['knowledge_requirements'])){
            $data['knowledge_requirements'] = $all['knowledge_requirements'];
        }
        if(isset($all['imgs'])){
            $data['imgs'] = $all['imgs'];
        }
        if(isset($all['tag'])){
            $data['tag'] = $all['tag'];
        }
        if(isset($all['personal_resume'])){
            $data['personal_resume'] = $all['personal_resume'];
        }
        if(isset($all['professional_skill'])){
            $data['professional_skill'] = $all['professional_skill'];
        }
        if(isset($all['educational_back'])){
            $data['educational_back'] = $all['educational_back'];
        }
        if(isset($all['work_experience'])){
            $data['work_experience'] = $all['work_experience'];
        }
        if(isset($all['certificate_reward'])){
            $data['certificate_reward'] = $all['certificate_reward'];
        }
        if(isset($all['self_assessment'])){
            $data['self_assessment'] = $all['self_assessment'];
        }
        if(isset($all['tag_me'])){
            $data['tag_me'] = $all['tag_me'];
        }
        if(isset($all['jxjh'])){
            $data['jxjh'] = $all['jxjh'];
        }
        if(isset($all['work_time'])){
            $data['work_time'] = $all['work_time'];
        }
        if(isset($all['education_background'])){
            $data['education_background'] = $all['education_background'];
        }
        if(isset($all['is_premium'])){
            $data['is_premium'] = $all['is_premium'];
        }
        if(isset($all['sort'])){
            $data['sort'] = $all['sort'];
        }
        if(isset($all['score'])){
            $data['score'] = $all['score'];
        }
        
        // 唯一性校验：同一教师不可同时存在 社团id 和 精品配置 相同的数据
        // 组合条件：info_id + club_two_id + is_premium
        $checkInfoId    = $find['info_id']; // API不允许改 info_id，直接用原值
        $checkClubTwoId = isset($data['club_two_id']) ? $data['club_two_id'] : $find['club_two_id'];
        $checkIsPremium = isset($data['is_premium']) ? $data['is_premium'] : $find['is_premium'];
        if ($checkInfoId && $checkClubTwoId) {
            $exists = TeacherDetail::where([
                    'info_id'     => $checkInfoId,
                    'club_two_id' => $checkClubTwoId,
                    'is_premium'  => $checkIsPremium,
                ])
                ->where('id', '<>', $find['id'])
                ->find();
            if ($exists) {
                $this->error('当前教师已存在相同的社团和精品设置');
            }
        }
        
        // 合并现有数据和新数据用于判断是否资料完整
        $updateData = array_merge($find->toArray(), $data);
        
        // 检查是否上传完整
        $detailComplete = $updateData['club_one_id'] && $updateData['club_two_id'] && 
                         !empty($updateData['teacher_certification']) &&
                         !empty($updateData['diploma']) &&
                         !empty($updateData['occupational_qualifications']) &&
                         !empty($updateData['professional_skill']);
        
        $identityInfo = \app\admin\model\IdentityInfo::where(['id'=>$find['info_id']])->find();
        $identityComplete = false;
        if($identityInfo){
            $identityComplete = !empty($identityInfo['health_certificate']) && 
                               !empty($identityInfo['identity_card_img']) && 
                               !empty($identityInfo['no_crime']);
        }
        
        $data['is_all'] = ($detailComplete && $identityComplete) ? '是' : '否';
        
        // 更新数据
        $result = TeacherDetail::where(['id'=>$all['id']])->update($data);
        if(isset($all['hourly_rate'])&&$all['hourly_rate']){
            $td_h = \app\admin\model\TeacherDetail::where(['info_id'=>$find['info_id']])->where("hourly_rate>0")->order('hourly_rate','asc')->find();
            if($td_h){
                if($td_h['hourly_rate']>$all['hourly_rate']){
                    \app\admin\model\IdentityInfo::where(['id'=>$find['info_id']])->update(['lowest_hourly_rate'=>$all['hourly_rate']]);
                }
            }
        }
        if($result !== false){
            // 生成Word文档
            \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $identityInfo['user_id'],'detail_id'=>$find['id']], 'default');
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }

    public function up_school_identity_info(){
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $all = $this->request->param();
        if(!isset($all['name'])||!$all['name']){
            $this->error('姓名不能为空');
        }

        if(!isset($all['phone'])||!$all['phone']){
            $this->error('电话不能为空');
        }
        if(!isset($all['school'])||!$all['school']){
            $this->error('学校不能为空');
        }
        $data = [];
        $data['school'] = $all['school'];//学校
        $data['name'] = $all['name'];//姓名
        $data['phone'] = $all['phone'];//电话

        $all['identity_type'] = '校方';
        $find = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->find();
        if(!$find){
            $this->error('校方身份不存在，不可修改');
        }
        if($find['phone']!=$data['phone']){
            $phone_find = \app\admin\model\IdentityInfo::where(['phone'=>$data['phone']])->where("user_id != {$user['id']}")->find();
            if($phone_find){
                $this->error('手机号已被其他账号使用');
            }
            $user_find = \app\admin\model\User::where(['mobile'=>$data['phone']])->where("id != {$user['id']}")->find();
            if($user_find){
                $this->error('手机号已被其他账号使用');
            }
        }
        $res = \app\admin\model\IdentityInfo::where(['user_id'=>$user['id'],'identity_type'=>$all['identity_type']])->update($data);

        $update = [];
        $update['nickname'] = $all['name'];
        if(isset($all['avatar'])&&$all['avatar']){
            $update['avatar'] = $all['avatar'];
        }
        if($find['phone']!=$data['phone']){
            $update['mobile'] = $data['phone'];
            $phone_user_find = \app\admin\model\User::where(['id'=>$user['id']])->find();
            if($phone_user_find['username'] == $phone_user_find['mobile']){
                $update['username'] = $data['phone'];
            }
        }
        $user_res = \app\admin\model\User::where(['id'=>$user['id']])->update($update);

        if($res||$user_res){
            $this->success('修改成功',$res);
        }else{
            $this->error('修改失败');
        }
    }



    //todo::以下内容应该已经废弃了
    /**
     * 生成教师身份信息Word文档
     */
    public function generate_word_document()
    {
//        $user = $this->auth->getUser();
//        if (!isset($user['id']) || !$user['id']) {
//            $this->error('当前登录用户不存在');
//        }
        $all = $this->request->param();
        if(!isset($all['user_id'])||!$all['user_id']){
            $this->error('用户id必传');
        }
        // 获取教师身份信息
        $identityInfo = \app\admin\model\IdentityInfo::where(['user_id' => $all['user_id'], 'identity_type' => '教师'])->with(['user','club_dtl_s'])->find();
        if (!$identityInfo) {
            $this->error('教师身份信息不存在');
        }
        $this->success('文档生成并上传成功', [
            'filename' => $identityInfo['name'],
            'oss_url' => $identityInfo['word_file'],
            'download_url' => $identityInfo['word_file']
        ]);

        exit;
        // 处理数据
        $data = $this->processIdentityData($identityInfo);
        
        // 生成Word文档
        $result = $this->createWordDocument($data);
        
        if ($result) {
            if (is_array($result) && isset($result['oss_url'])) {
                // 上传到OSS成功
                $this->success('文档生成并上传成功', [
                    'filename' => $result['filename'],
                    'oss_url' => $result['oss_url'],
                    'download_url' => $result['oss_url']
                ]);
            } else {
                // 本地保存成功
                $this->success('文档生成成功', [
                    'filename' => $result,
                    'download_url' => '/api/identity_info/download_word?filename=' . urlencode($result)
                ]);
            }
        } else {
            $this->error('文档生成失败');
        }
    }

    /**
     * 处理身份信息数据
     */
    private function processIdentityData($identityInfo)
    {
        $data = $identityInfo->toArray();
        
        // 处理图片数组
        $data['img_arr'] = $identityInfo['imgs'] ? explode(',', $identityInfo['imgs']) : [];
        $data['teacher_certification_arr'] = $identityInfo['teacher_certification'] ? explode(',', $identityInfo['teacher_certification']) : [];
        $data['diploma_arr'] = $identityInfo['diploma'] ? explode(',', $identityInfo['diploma']) : [];
        $data['occupational_qualifications_arr'] = $identityInfo['occupational_qualifications'] ? explode(',', $identityInfo['occupational_qualifications']) : [];
        $data['professional_skill_arr'] = $identityInfo['professional_skill'] ? explode(',', $identityInfo['professional_skill']) : [];
        $data['health_certificate_arr'] = $identityInfo['health_certificate'] ? explode(',', $identityInfo['health_certificate']) : [];
        $data['identity_card_img_arr'] = $identityInfo['identity_card_img'] ? explode(',', $identityInfo['identity_card_img']) : [];
        $data['no_crime_arr'] = $identityInfo['no_crime'] ? explode(',', $identityInfo['no_crime']) : [];
        
        // 处理区域名称
        $area = $identityInfo['area'] ? explode(',', $identityInfo['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k => $v) {
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v] . ',' : '';
        }
        $data['area_name'] = trim($area_name, ',');
        
        // 处理用户性别
        $user = $this->auth->getUser();
        $user_find = \app\admin\model\User::where(['id' => $user['id']])->find();
        if ($user_find['gender'] == 1) {
            $data['sex'] = '男';
        } else {
            $data['sex'] = '女';
        }
        
        // 处理工作年限
        $data['work_time_display'] = $identityInfo['work_time'] ? $identityInfo['work_time'] . '年' : '';
        $data['club_dtl_name'] = isset($identityInfo['club_dtl_s']) ? $identityInfo['club_dtl_s']['name'] : '';
        $data['avatar'] = isset($identityInfo['user']) ? $identityInfo['user']['avatar'] : '';
        return $data;
    }

    /**
     * 创建Word文档
     */
    private function createWordDocument($data)
    {
        try {
            // 创建PHPWord对象
            $phpWord = new PhpWord();
            
            // 设置文档属性
            $phpWord->getDocInfo()->setCreator('下午活动中心')
                ->setLastModifiedBy('下午活动中心')
                ->setTitle('教师身份信息表')
                ->setSubject('教师身份信息')
                ->setDescription('教师身份信息详细资料')
                ->setKeywords('教师,身份信息,下午活动中心')
                ->setCategory('身份信息');

            // 设置默认字体
            $phpWord->setDefaultFontName('微软雅黑');
            $phpWord->setDefaultFontSize(12);

            // 添加标题
            $phpWord->addTitleStyle(1, ['name' => '微软雅黑', 'size' => 18, 'bold' => true], ['alignment' => 'center']);
            $phpWord->addTitleStyle(2, ['name' => '微软雅黑', 'size' => 14, 'bold' => true]);
            $phpWord->addTitleStyle(3, ['name' => '微软雅黑', 'size' => 12, 'bold' => true]);

            // 开始添加内容
            $section = $phpWord->addSection([
                'marginTop' => 1134,
                'marginBottom' => 1134,
                'marginLeft' => 1134,
                'marginRight' => 1134,
            ]);

            // 主标题
            $section->addTitle('教师身份信息表', 1);
            $section->addTextBreak(1);

            // 基本信息
            $section->addTitle('一、基本信息', 2);
            $this->addBasicInfo($section, $data);
            $section->addTextBreak(1);

            // 教育背景
            $section->addTitle('二、个人简历', 2);
            $this->addEducationInfo($section, $data);
            $section->addTextBreak(1);

            // 工作经历
            $section->addTitle('三、教师资质', 2);
            $this->addWorkExperience($section, $data);
            $section->addTextBreak(1);

            // 专业技能
            $section->addTitle('四、课程信息', 2);
            $this->addProfessionalSkills($section, $data);
            $section->addTextBreak(1);
//
//            // 身份证明
//            $section->addTitle('五、身份证明', 2);
//            $this->addIdentityDocuments($section, $data);
//            $section->addTextBreak(1);
//
//            // 教学信息
//            $section->addTitle('六、教学信息', 2);
//            $this->addTeachingInfo($section, $data);
//            $section->addTextBreak(1);
//
//            // 其他信息
//            $section->addTitle('七、其他信息', 2);
//            $this->addOtherInfo($section, $data);

            // 生成文件名
            $filename = $data['name'] . '_教师身份信息_' . date('YmdHis') . '.docx';
            $filepath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'word' . DS;
            
            // 确保目录存在
            if (!is_dir($filepath)) {
                mkdir($filepath, 0755, true);
            }
            
            $fullPath = $filepath . $filename;
            
            // 保存文档
            $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
            $objWriter->save($fullPath);
            
            // 上传到OSS
            $ossUrl = $this->uploadToOSS($fullPath, $filename);
            
            // 清理临时文件
            $this->cleanupTempFiles();
            
            // 删除本地文件（如果上传成功）
            if ($ossUrl) {
                @unlink($fullPath);
                return ['filename' => $filename, 'oss_url' => $ossUrl];
            }
            
            return $filename;
            
        } catch (\Exception $e) {
            \think\Log::error('生成Word文档失败: ' . $e->getMessage());
            // 即使出错也要清理临时文件
            $this->cleanupTempFiles();
            return false;
        }
    }

    /**
     * 清理临时文件
     */
    private function cleanupTempFiles()
    {
        foreach ($this->tempFiles as $tempFile) {
            if (file_exists($tempFile)) {
                @unlink($tempFile);
                \think\Log::info('删除临时文件: ' . $tempFile);
            }
        }
        // 清空临时文件列表
        $this->tempFiles = [];
    }

    /**
     * 上传文件到OSS
     */
    private function uploadToOSS($filePath, $filename)
    {
        try {
            // 获取OSS配置
            $config = get_addon_config('alioss');
            if (!$config) {
                \think\Log::error('OSS配置不存在');
                return false;
            }

            // 创建OSS客户端
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

            // 生成OSS存储路径
            $ossKey = '/uploads/word/' . date('Ymd') . '/' . $filename;
            
            \think\Log::info('开始上传文件到OSS: ' . $filePath . ' -> ' . $ossKey);

            // 上传文件到OSS
            $result = $ossClient->uploadFile($config['bucket'], ltrim($ossKey, '/'), $filePath);
            
            if ($result && isset($result['info']['url'])) {
                $ossUrl = $result['info']['url'];
                \think\Log::info('文件上传到OSS成功: ' . $ossUrl);
                return $ossUrl;
            } else {
                \think\Log::error('OSS上传失败，未返回URL');
                return false;
            }

        } catch (OssException $e) {
            \think\Log::error('OSS上传异常: ' . $e->getMessage());
            return false;
        } catch (\Exception $e) {
            \think\Log::error('上传文件到OSS失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 添加基本信息
     */
    private function addBasicInfo($section, $data)
    {
        $table = $section->addTable(['borderSize' => 6, 'borderColor' => '000000']);
        
        $this->addTableRow($table, '姓名', $data['name'] ?? '');
        $this->addTableRow($table, '电话', $data['phone'] ?? '');
        $this->addTableRow($table, '年龄', $data['age'] ?? '');
        $this->addTableRow($table, '性别', $data['sex'] ?? '');
        $this->addTableRow($table, '教学经验', $data['work_time_display'] ?? '');
        $this->addTableRow($table, '最高学历', $data['education_background'] ?? '');
        $this->addTableRow($table, '所属社团', $data['club_dtl_name'] ?? '');
        $this->addTableRow($table, '服务区域', $data['area_name'] ?? '');
        $this->addTableRow($table, '课时费用', ($data['hourly_rate'] ?? '') . '元/节');
        $this->addTableRow($table, '可约时间', ($data['appointment_time_week'] ?? '') . ' ' . ($data['appointment_time'] ?? ''));
        
        // 添加头像
        if (!empty($data['avatar']) && $this->isImagePath($data['avatar'])) {
            $section->addText('头像:', ['bold' => true]);
            $this->addImageToSection($section, $data['avatar'], '头像');
        }
        // 封面图片
        if (!empty($data['img_arr'])) {
            $section->addText('封面图片:', ['bold' => true]);
            foreach ($data['img_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '封面图片');
                }
            }
        }
    }

    /**
     * 添加个人简历
     */
    private function addEducationInfo($section, $data)
    {
        if (!empty($data['educational_back'])) {
            $section->addText('教育背景:', ['bold' => true]);
            $section->addText($data['educational_back']);
            $section->addTextBreak(1);
        }
        if (!empty($data['work_experience'])) {
            $section->addText('工作经历:', ['bold' => true]);
            $section->addText($data['work_experience']);
            $section->addTextBreak(1);
        }
        if (!empty($data['certificate_reward'])) {
            $section->addText('证书奖励:', ['bold' => true]);
            $section->addText($data['certificate_reward']);
            $section->addTextBreak(1);
        }

        if (!empty($data['self_assessment'])) {
            $section->addText('自我评价:', ['bold' => true]);
            $section->addText($data['self_assessment']);
            $section->addTextBreak(1);
        }
    }

    /**
     * 添加教师资质
     */
    private function addWorkExperience($section, $data)
    {
        // 教师资格证
        if (!empty($data['teacher_certification_arr'])) {
            $section->addText('教师资格证:', ['bold' => true]);
            foreach ($data['teacher_certification_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '教师资格证');
                }
            }
        }
        // 职业资格证书
        if (!empty($data['occupational_qualifications_arr'])) {
            $section->addText('获奖证书:', ['bold' => true]);
            foreach ($data['occupational_qualifications_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '获奖证书');
                }
            }
        }
        // 毕业证书
        if (!empty($data['diploma_arr'])) {
            $section->addText('毕业证书:', ['bold' => true]);
            foreach ($data['diploma_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '毕业证书');
                }
            }
        }

    }

    /**
     * 添加课程信息
     */
    private function addProfessionalSkills($section, $data)
    {

        if (!empty($data['course_outline'])) {
            $section->addText('课程简介:', ['bold' => true]);
            $section->addText($data['course_outline']);
            $section->addTextBreak(1);
        }

        if (!empty($data['teaching_objectives'])) {
            $section->addText('教学目标:', ['bold' => true]);
            $section->addText($data['teaching_objectives']);
            $section->addTextBreak(1);
        }
//
//        if (!empty($data['knowledge_requirements'])) {
//            $section->addText('预备知识要求:', ['bold' => true]);
//            $section->addText($data['knowledge_requirements']);
//            $section->addTextBreak(1);
//        }

        if (!empty($data['jxjh'])) {
            $section->addText('教学计划:', ['bold' => true]);
            $section->addText($data['jxjh']);
            $section->addTextBreak(1);
        }

//        // 专业技能证书
//        if (!empty($data['professional_skill_arr'])) {
//            $section->addText('专业技能证书:', ['bold' => true]);
//            foreach ($data['professional_skill_arr'] as $image) {
//                if ($this->isImagePath($image)) {
//                    $this->addImageToSection($section, $image, '专业技能证书');
//                }
//            }
//        }
    }

    /**
     * 添加身份证明
     */
    private function addIdentityDocuments($section, $data)
    {
        // 身份证
        if (!empty($data['identity_card_img_arr'])) {
            $section->addText('身份证复印件:', ['bold' => true]);
            foreach ($data['identity_card_img_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '身份证');
                }
            }
        }
        
        // 健康证
        if (!empty($data['health_certificate_arr'])) {
            $section->addText('健康证:', ['bold' => true]);
            foreach ($data['health_certificate_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '健康证');
                }
            }
        }
        
        // 无犯罪证明
        if (!empty($data['no_crime_arr'])) {
            $section->addText('无犯罪证明:', ['bold' => true]);
            foreach ($data['no_crime_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '无犯罪证明');
                }
            }
        }
    }

    /**
     * 添加教学信息
     */
    private function addTeachingInfo($section, $data)
    {
    }

    /**
     * 添加其他信息
     */
    private function addOtherInfo($section, $data)
    {


    }

    /**
     * 添加表格行
     */
    private function addTableRow($table, $label, $value)
    {
        $table->addRow();
        $table->addCell(2000)->addText($label, ['bold' => true]);
        $table->addCell(4000)->addText($value);
    }

    /**
     * 添加图片到文档
     */
    private function addImageToSection($section, $imagePath, $altText = '')
    {
        try {
            $localPath = $this->downloadImageToLocal($imagePath);
            if ($localPath && file_exists($localPath)) {
                $section->addImage($localPath, [
                    'width' => 300,
                    'height' => 200,
                    'alignment' => 'left'
                ]);
                $section->addTextBreak(1);
                
                // 将临时文件路径添加到待删除列表，稍后统一删除
                $this->tempFiles[] = $localPath;
            }
        } catch (\Exception $e) {
            \think\Log::error('添加图片失败: ' . $e->getMessage());
        }
    }

    /**
     * 下载图片到本地临时目录
     */
    private function downloadImageToLocal($imagePath)
    {
        try {
            // 获取完整的图片URL
            $imageUrl = $this->getImageFullPath($imagePath);
            \think\Log::info('图片URL: ' . $imageUrl);
            
            // 如果是本地文件，直接返回
            if (strpos($imageUrl, 'http') !== 0) {
                $result = file_exists($imageUrl) ? $imageUrl : null;
                \think\Log::info('本地文件检查: ' . ($result ? '存在' : '不存在'));
                return $result;
            }
            
            // 创建临时目录
            $tempDir = ROOT_PATH . 'runtime' . DS . 'temp' . DS . 'word_images' . DS;
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0755, true);
            }
            
            // 生成临时文件名
            $extension = pathinfo($imagePath, PATHINFO_EXTENSION);
            $tempFileName = uniqid() . '_' . time() . '.' . $extension;
            $tempFilePath = $tempDir . $tempFileName;
            
            \think\Log::info('临时文件路径: ' . $tempFilePath);
            
            // 下载图片
            $imageData = $this->downloadImageFromUrl($imageUrl);
            if ($imageData === false || empty($imageData)) {
                \think\Log::error('图片下载失败或数据为空');
                return null;
            }
            
            \think\Log::info('图片数据大小: ' . strlen($imageData) . ' bytes');
            
            // 保存到临时文件
            $result = file_put_contents($tempFilePath, $imageData);
            if ($result === false) {
                \think\Log::error('保存临时文件失败');
                return null;
            }
            
            \think\Log::info('图片保存成功: ' . $tempFilePath);
            return $tempFilePath;
            
        } catch (\Exception $e) {
            \think\Log::error('下载图片失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 从URL下载图片
     */
    private function downloadImageFromUrl($url)
    {
        try {
            \think\Log::info('开始下载图片: ' . $url);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Accept: image/webp,image/apng,image/*,*/*;q=0.8',
                'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
                'Cache-Control: no-cache'
            ]);
            
            $data = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            \think\Log::info('HTTP状态码: ' . $httpCode);
            if ($error) {
                \think\Log::error('CURL错误: ' . $error);
            }
            
            if ($httpCode === 200 && $data !== false && !empty($data)) {
                \think\Log::info('图片下载成功，数据大小: ' . strlen($data) . ' bytes');
                return $data;
            }
            
            \think\Log::error('图片下载失败 - HTTP状态码: ' . $httpCode . ', 数据大小: ' . strlen($data));
            return false;
            
        } catch (\Exception $e) {
            \think\Log::error('下载图片异常: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取图片完整路径
     */
    private function getImageFullPath($imagePath)
    {
        // 如果已经是完整的URL，直接返回
        if (strpos($imagePath, 'http') === 0) {
            return $imagePath;
        }
        
        // 如果是相对路径，拼接OSS域名
        if (strpos($imagePath, '/uploads/') === 0) {
            return 'https://ev-2022.oss-cn-shenzhen.aliyuncs.com' . $imagePath;
        }
        
        return $imagePath;
    }

    /**
     * 判断是否为图片路径
     */
    private function isImagePath($path)
    {
        if (empty($path)) {
            return false;
        }
        
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        
        return in_array($extension, $imageExtensions);
    }

    /**
     * 简单的API测试
     */
    public function test()
    {
        $this->success('API测试成功', [
            'time' => date('Y-m-d H:i:s'),
            'method' => $this->request->method(),
            'params' => $this->request->param()
        ]);
    }

    /**
     * 测试图片下载
     */
    public function test_image_download()
    {
        $all = $this->request->param();
        if (!isset($all['image_url']) || !$all['image_url']) {
            $this->error('图片URL不能为空');
        }
        
        $imageUrl = $all['image_url'];
        \think\Log::info('测试图片URL: ' . $imageUrl);
        
        // 测试下载
        $imageData = $this->downloadImageFromUrl($imageUrl);
        
        if ($imageData === false) {
            $this->error('图片下载失败');
        }
        
        // 保存测试图片
        $testDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'test' . DS;
        if (!is_dir($testDir)) {
            mkdir($testDir, 0755, true);
        }
        
        $testFileName = 'test_image_' . time() . '.jpg';
        $testFilePath = $testDir . $testFileName;
        file_put_contents($testFilePath, $imageData);
        
        $this->success('图片下载成功', [
            'original_url' => $imageUrl,
            'data_size' => strlen($imageData),
            'test_file' => '/uploads/test/' . $testFileName,
            'test_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/test/' . $testFileName
        ]);
    }

    /**
     * 下载Word文档
     */
    public function downloadWord()
    {
        $filename = $this->request->param('filename');
        if (empty($filename)) {
            $this->error('文件名不能为空');
        }
        
        $filepath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'word' . DS . $filename;
        
        if (!file_exists($filepath)) {
            $this->error('文件不存在');
        }
        
        // 设置下载头
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        
        // 输出文件
        readfile($filepath);
        exit;
    }

    /**
     * 批量修改课程显示状态（下架/显示）
     * 只能批量操作自己的课程
     * @param ids 课程ID，支持逗号分隔字符串或数组
     * @param status 状态：1显示，2下架
     */
    public function batch_course_status()
    {
        $params = $this->request->param();
        if (!isset($params['ids']) || empty($params['ids'])) {
            $this->error('请选择要操作的课程');
        }
        
        if (!isset($params['status']) || !in_array((int)$params['status'], [1, 2])) {
            $this->error('状态参数错误，只能是1（显示）或2（下架）');
        }
        
        $user = $this->auth->getUser();
        if (!isset($user['id']) || !$user['id']) {
            $this->error('当前登录用户不存在');
        }
        
        // 处理ids，支持逗号分隔的字符串或数组
        if (is_string($params['ids'])) {
            $ids = explode(',', $params['ids']);
        } else {
            $ids = $params['ids'];
        }
        
        // 过滤空值并转换为整数
        $ids = array_filter(array_map('intval', $ids));
        if (empty($ids)) {
            $this->error('课程ID不能为空');
        }
        
        // 只能操作当前用户的课程
        $identity_info = \app\admin\model\IdentityInfo::where(['user_id' => $user['id'], 'identity_type' => '教师'])->find();
        if (!$identity_info) {
            $this->error('用户身份不存在');
        }
        
        $status = (int)$params['status'];
        $result = TeacherDetail::where(['info_id' => $identity_info['id']])
            ->whereIn('id', $ids)
            ->update(['detail_status' => $status]);
        
        if ($result) {
            $msg = $status == 1 ? '批量显示成功' : '批量下架成功';
            $this->success($msg, ['count' => $result]);
        } else {
            $msg = $status == 1 ? '批量显示失败' : '批量下架失败';
            $this->error($msg);
        }
    }

}
